import axios from 'axios'
import { handleLocalUserInfo } from '@/utils/utils'
import { refreshToken } from '@/api/user'
import Toast from '@/components/toast'

const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_PATH,
  timeout: 100000,
})

const { getUserToken, setUserToken, clearUserToken } = handleLocalUserInfo()

service.interceptors.request.use(
  (config) => {
    // 注入用户token
    const tokenObj = getUserToken()
    if (tokenObj.token) {
      config.headers['Authorization'] = `Bearer ${tokenObj.token}`
    }
    return config
  },
  (error) => {
    return error
  }
)

// 避免频繁发送更新
let refreshing = false
// 请求队列
const requestQueue = []

service.interceptors.response.use(
  async (response) => {
    const { code, msg } = response.data
    const { config } = response
    const tokenObj = getUserToken()
    // 需要跳过刷新token的请求验证
    if (refreshing && !config.url.includes('/refreshToken')) {
      return new Promise((resolve) => {
        requestQueue.push({
          config,
          resolve,
        })
      })
    }
    if (code === 401 && !config.url.includes('/refreshToken')) {
      refreshing = true
      const res = await refreshToken(tokenObj.refreshToken)
      refreshing = false
      if (!res.code) {
        // 保存token
        setUserToken(res.data.token)
        // 执行缓存队列里的请求
        requestQueue.forEach(({ config, resolve }) => {
          resolve(service(config))
        })
        // 执行当次请求
        return service(config)
      } else {
        clearUserToken()
        // 去登陆
        if (window.location.pathname !== '/login' && window.location.pathname !== '/') {
          window.location.replace('/login')
        }
      }
    }
    // 处理异常请求
    if (code === 500) {
      if (config.url !== 'api/marketing/alliance/link') {
        Toast.error(msg)
      }
    }
    return response.data
  },
  (error) => {
    return error
  }
)
export default service
